package com.yb0os1.serve.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yb0os1.constant.MessageConstant;
import com.yb0os1.context.BaseContext;
import com.yb0os1.dto.OrderCancelDTO;
import com.yb0os1.dto.OrderConditionSearchDTO;
import com.yb0os1.dto.OrderRejectDTO;
import com.yb0os1.dto.OrderSubmitDTO;
import com.yb0os1.dto.OrdersPaymentDTO;
import com.yb0os1.entity.AddressBook;
import com.yb0os1.entity.OrderDetail;
import com.yb0os1.entity.Orders;
import com.yb0os1.entity.ShoppingCart;
import com.yb0os1.exception.AddressBookBusinessException;
import com.yb0os1.exception.OrderBusinessException;
import com.yb0os1.exception.ShoppingCartBusinessException;
import com.yb0os1.mapper.AddressBookMapper;
import com.yb0os1.mapper.OrderDetailMapper;
import com.yb0os1.mapper.OrderMapper;
import com.yb0os1.mapper.ShoppingCartMapper;
import com.yb0os1.mapper.UserMapper;
import com.yb0os1.result.PageResult;
import com.yb0os1.serve.OrderServe;
import com.yb0os1.utils.WeChatPayUtil;
import com.yb0os1.vo.OrderPaymentVO;
import com.yb0os1.vo.OrderStatisticsVO;
import com.yb0os1.vo.OrderSubmitVO;
import com.yb0os1.vo.OrderVO;
import com.yb0os1.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServeImpl implements OrderServe {
    @Override
    public void reminderOrder(Long id) {
        Orders order = orderMapper.getById(BaseContext.getCurrentId(), id);
        //是否存在该订单
        if (order==null)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        //进行对外卖商家的提醒
        Map map = new HashMap();
        map.put("type",2);//type 1 =》来单提醒   type 2=》用户催单
        map.put("orderId",id);
        map.put("content","订单号"+order.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    @Override
    public void completeOrder(Long id) {
        orderMapper.update(Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build());
    }

    @Override
    public OrderStatisticsVO orderStatistics() {
        Integer confirmed = orderMapper.statistics(Orders.CONFIRMED);
        Integer toBeConfirmed = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
        Integer deliveryInProgress = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);
        return OrderStatisticsVO.builder().toBeConfirmed(toBeConfirmed).confirmed(confirmed).deliveryInProgress(deliveryInProgress).build();
    }

    @Override
    public void sendOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    @Override
    @Transactional
    public void repetitionOrder(Long id) {
        //再来一单是直接加入购物车！！！
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).toList();

        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrderSubmitDTO orderSubmitDTO) {
        log.info("提交购物车{}", orderSubmitDTO);
        //处理业务异常（地址为空 购物车为空）
        AddressBook addressBook = addressBookMapper.getById(orderSubmitDTO.getAddressBookId());
        if (addressBook == null)
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty())
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        orderMapper.insert(orders);
        //向订单明细表插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车数据
        shoppingCartMapper.cleanAll(userId);
        //返回VO对象
        return OrderSubmitVO.builder().id(orders.getId()).orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber()).orderAmount(orders.getAmount())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        this.paySuccess(ordersPaymentDTO.getOrderNumber());
        //支付完成之后 管理端有来单提醒
        //服务端给客户端发送信息 此时客户端是浏览器
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orderMapper.getIdByOrderNumber(ordersPaymentDTO.getOrderNumber()));
        map.put("content","订单号"+ordersPaymentDTO.getOrderNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    @Override
    public OrderVO getOrderById(Long id) {
        Orders order = orderMapper.getById(BaseContext.getCurrentId(), id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
//        AddressBook addressBook = addressBookMapper.getById(order.getAddressBookId());
        return orderVO;
    }

    @Override
    public PageResult conditionSearch(OrderConditionSearchDTO orderConditionSearchDTO) {
        PageHelper.startPage(orderConditionSearchDTO.getPage(), orderConditionSearchDTO.getPageSize());
        orderConditionSearchDTO.setUserId(BaseContext.getCurrentId());
        List<Orders> orders = orderMapper.list(orderConditionSearchDTO);
        Page<Orders> p = (Page<Orders>) orders;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public void confirmOrder(Long id) {
        orderMapper.update(Orders.builder().id(id).status(Orders.CONFIRMED).build());
    }

    @Override
    public void rejectionOrder(OrderRejectDTO orderRejectDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(BaseContext.getCurrentId(), orderRejectDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            log.info("退款");
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        orderMapper.update(Orders.builder()
                .id(orderRejectDTO.getId())
                .rejectionReason(orderRejectDTO.getRejectionReason())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build());
    }

    @Override
    public PageResult getHistoryOrders(OrderConditionSearchDTO orderConditionSearchDTO) {
        PageHelper.startPage(orderConditionSearchDTO.getPage(), orderConditionSearchDTO.getPageSize());
        orderConditionSearchDTO.setUserId(BaseContext.getCurrentId());
        List<Orders> orders = orderMapper.list(orderConditionSearchDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(order.getId());
            orderVO.setOrderDetailList(byOrderId);
            orderVOList.add(orderVO);
        }
        PageInfo<OrderVO> p = new PageInfo<>(orderVOList);
        return new PageResult(p.getTotal(), p.getList());
    }

    @Override
    public void cancelOrder(Long id) {
        orderMapper.update(Orders.builder()
                .id(id)
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build()
        );
    }

    @Override
    public void cancelOrder(OrderCancelDTO orderCancelDTO) {
        orderMapper.update(Orders.builder()
                .id(orderCancelDTO.getId())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .cancelReason(orderCancelDTO.getCancelReason())
                .build()
        );
    }
}
